import os
import sys
import time
import shutil
import json

def get_modify_time(file):
    return os.stat(file).st_mtime_ns

def check_modify_time(file,meta_json):
    modified=False
    filename=os.path.basename(file)
    m_time=get_modify_time(file)
    if filename not in meta_json:
        meta_json[filename]=m_time
        modified=True
    else:
        if meta_json[filename]!=m_time:
            modified=True
    meta_json[filename]=m_time
    return modified

def modify_load_config(configs):
    if os.path.exists(os.path.join(configs.work_dir,os.path.pardir,os.path.pardir,"load_config.json")):
        shutil.copy(os.path.join(configs.work_dir,os.path.pardir,os.path.pardir,"load_config.json"),
                    os.path.join(configs.cache_repo,os.path.pardir,os.path.pardir,"load_config.json"))

    with open(os.path.join(configs.cache_repo,os.path.pardir,os.path.pardir,"load_config.json"),'w+') as f:
        try:
            meta_json=json.load(f)
        except Exception:
            meta_json=dict()

        if not "load_versions" in meta_json:
            meta_json["load_versions"]=[]
        load_versions=meta_json["load_versions"]

        version_item={"version":configs.model_version}
        found_in_config=False
        for item in load_versions:
            if not "version" in item:
                continue

            if item["version"] == configs.model_version:
                version_item=item["version"]
                found_in_config=True
                break

        if not found_in_config:
            load_versions.append(version_item)

        if not "backend" in version_item:
            version_item["backend"]=[]

        if not configs.targe_framework in version_item["backend"]:
            version_item["backend"].append(configs.targe_framework)

        json.dump(meta_json,f)